package com.bluemsun.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author Steve Paul
 */
public class Register extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        //获取输入进来的用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //读取文件中的用户名和密码,然后一一对应查找是否有重复
        File users = new File(getServletContext().getRealPath("/") + "WEB-INF/classes/users");
        BufferedReader br = new BufferedReader(new FileReader(users));
        String input;
        String[] splitInput;
        boolean isRepeat = false;
        while ((input = br.readLine()) != null) {
            splitInput = input.split(" ");
            if (username.equals(splitInput[0])) {
                isRepeat = true;
                break;
            }
        }
        br.close();
        //有重复则提醒,没有重复则新注册该用户
        if (isRepeat) {
            pw.println("该用户名已存在!<br>");
        } else {
            BufferedWriter bw = new BufferedWriter(new FileWriter(users,true));
            bw.write(username + " " + password + "\n");
            bw.flush();
            bw.close();
            pw.println("已成功注册该用户<br>");
        }
        pw.close();
    }
}
